package com.sixj.keycloak;

import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.storage.UserStorageProviderFactory;

import java.util.ArrayList;
import java.util.List;

public class EmployeeUserStorageProviderFactory implements UserStorageProviderFactory<EmployeeUserStorageProvider> {
    private static final Logger logger = Logger.getLogger(EmployeeUserStorageProviderFactory.class);

    public static final String PROVIDER_ID = "employee-user-storage";

    @Override
    public String getId() {
        return PROVIDER_ID;
    }

    @Override
    public EmployeeUserStorageProvider create(KeycloakSession session, ComponentModel model) {

        return new EmployeeUserStorageProvider(session, model);
    }
    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        List<ProviderConfigProperty> config = new ArrayList<>();

        ProviderConfigProperty jdbcUrl = new ProviderConfigProperty();
        jdbcUrl.setName("jdbcUrl");
        jdbcUrl.setLabel("JDBC URL");
        jdbcUrl.setType("String");
        jdbcUrl.setDefaultValue("jdbc:mysql://192.168.173.39:3306/middleground?serverTimezone=Asia/Shanghai&useSSL=false");
        jdbcUrl.setHelpText("例如：jdbc:mysql://127.0.0.1:3306/yourdb?serverTimezone=Asia/Shanghai&useSSL=false");
        config.add(jdbcUrl);

        ProviderConfigProperty jdbcUser = new ProviderConfigProperty();
        jdbcUser.setName("jdbcUser");
        jdbcUser.setLabel("数据库用户名");
        jdbcUser.setType("String");
        jdbcUser.setDefaultValue("dbadmin");
        jdbcUser.setHelpText("MySQL 数据库用户名");
        config.add(jdbcUser);

        ProviderConfigProperty jdbcPassword = new ProviderConfigProperty();
        jdbcPassword.setName("jdbcPassword");
        jdbcPassword.setLabel("数据库密码");
        jdbcPassword.setType("Password");
        jdbcPassword.setDefaultValue("db_master");
        jdbcPassword.setHelpText("MySQL 数据库密码");
        config.add(jdbcPassword);

        return config;
    }

    @Override
    public void init(org.keycloak.Config.Scope config) {
        // 可选：初始化全局配置，无需处理可留空
    }

    @Override
    public void postInit(KeycloakSessionFactory factory) {
        // 可选：Keycloak启动后回调，无需处理可留空
    }

    @Override
    public void close() {
        // 资源清理，如无资源可留空
    }
    /**
     * 验证数据库连接是否正常
     *
     * @param session
     * @param realm
     * @param config
     * @throws ComponentValidationException
     */
    @Override
    public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel config) throws ComponentValidationException {
        // 检查JDBC配置
        String jdbcUrl = config.getConfig().getFirst("jdbcUrl");
        String jdbcUser = config.getConfig().getFirst("jdbcUser");
        String jdbcPwd  = config.getConfig().getFirst("jdbcPassword");
        if (jdbcUrl == null || jdbcUrl.isEmpty()) {
            throw new ComponentValidationException("JDBC URL不能为空！");
        }
        if (jdbcUser == null || jdbcUser.isEmpty()) {
            throw new ComponentValidationException("数据库用户名不能为空！");
        }
        if (jdbcPwd == null || jdbcPwd.isEmpty()) {
            throw new ComponentValidationException("数据库密码不能为空！");
        }
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            logger.info("MySQL JDBC Driver found！");
        } catch (ClassNotFoundException e) {
            logger.error("MySQL JDBC Driver not found！", e);
        }

        // 可选：检测数据库连通性
        try (java.sql.Connection conn = java.sql.DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd)) {
            // 成功则不抛异常
            logger.info("DB connection successfully! JDBC URL：" + jdbcUrl + ", user=" + jdbcUser);
        } catch (Exception e) {
            logger.error("DB connection failed ！JDBC URL: " + jdbcUrl + ", user: " + jdbcUser, e);
            throw new ComponentValidationException("数据库连接失败: " + e.getMessage());
        }
    }

}
